'''
1 加密的数据是user.id
2 加密算法 pip install pyjwt
3 密钥为SECRETKey
'''
import jwt,time
from flask import current_app
from functools import wraps
from flask import request
#生成token
def generate_token(data):
    #data数据类型是字典
    data.update({'exp': time.time()+current_app.config['JWT_EXPIRATION_DELTA']})
    token=jwt.encode(data,current_app.config['SECRET_KEY'],algorithm='HS256')
    return token


def verify_token(token):
    try:
        data=jwt.decode(token,current_app.config['SECRET_KEY'],algorithms=['HS256'])
    except Exception as e:
        return None
    return data

def login_required(view_func):
    @wraps(view_func)
    def verify_token_info(*arg,**kwargs):
        #获取用户传递的token
        token=request.headers.get('token')
        if verify_token(token):
            return view_func(*arg,**kwargs)
        else:
            return{
                'status':401, #这里返回到前端就是response.data.status
                'msg':'token无效'
            }
    return verify_token_info